package com.situ.yB2C.user.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.situ.yB2C.cart.dao.CartDao;
import com.situ.yB2C.cart.pojo.Cart;
import com.situ.yB2C.user.dao.UserDao;
import com.situ.yB2C.user.pojo.User;
import com.situ.yB2C.user.service.UserService;
import com.situ.yB2C.util.ContextUtil;
import com.situ.yB2C.util.DESUtil;
import com.situ.yB2C.util.MD5Util;



@Service
public class UserServiceImpl implements UserService {
	private static final Logger LOG = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	private UserDao userDao;
	@Autowired
	private CartDao cartDao;

	// 商城后台 的
	@Override
	public int saveUser(User user, MultipartFile partFile, String realPath) {

		// 准备上传文件的相对路径，这个路径需要保存到数据库中
		String fileName = partFile.getOriginalFilename();
		StringBuilder filePath = new StringBuilder();
		filePath.append("uploads/avator/").append(Calendar.getInstance().getTimeInMillis())
				.append(fileName.substring(fileName.lastIndexOf(".")));
		LOG.debug("相对路径=" + filePath);
		// 通过调用 MultipartFile de transferTo方法，将文件写出到磁盘中
		LOG.debug("文件写出的绝对路径" + realPath + fileName);
		File toFile = new File(realPath + filePath);
		// 得到写出文件的父目录
		File parentFile = toFile.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		try {
			partFile.transferTo(toFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}

		System.out.println(user.toString());
		user.setIsLock(1);
		user.setLoginCount(0);
		user.setActiveFlag(1);
		user.setCreateBy("admin");
		user.setCreateDate(new Date());

		return userDao.insert(user);
	}

	// 商城 的
	@Override
	public int saveUser1(User user) {
		System.out.println(user.toString());
		//需要对用户的密码进行加密
		user.setUserPass(MD5Util.encode(user.getUserPass())); 
		user.setUserKind(User.USER_KIND_BUYER);
		user.setIsLock(1);
		user.setLoginCount(0);
		user.setActiveFlag(1);
		user.setCreateBy("admin");
		user.setCreateDate(new Date());
		return userDao.insert(user);
	}

	@Override
	public User findUserById(Long rowId) {
		return userDao.selectOne(rowId);
	}

	@Override
	public int updateUser(User user) {
		Long rowId = user.getRowId();
		// 现根据主键查询一个所有旧数据的对象
		User editUser = userDao.selectOne(rowId);
		// 使用修改表单中的新的数据覆盖旧对象中的属性。
		editUser.setUserName(user.getUserName());
		editUser.setUserCode(user.getUserCode());
		editUser.setUserPass(user.getUserPass());
		editUser.setUserKind(user.getUserKind());
		editUser.setActiveFlag(1);
		editUser.setUpdateBy("admin");
		editUser.setUpdateDate(new Date());

		// 最后update 一个具有旧数据 + 新数据的对象
		return userDao.update(editUser);
	}

	@Override
	public int deleteUser(Long rowId) {

		return userDao.delete(rowId);
	}

	@Override
	public List<User> findAllUser() {

		return userDao.selectList();
	}

	@Override
	public int doDeleteUserById(Long rowId) {

		return userDao.delete(rowId);
	}

	@Override
	public int doUserLogin(String userCode, String userPass, HttpSession session) {
		int result = 0;

		// System.out.println(userCode);
		User user = userDao.selectOneByCodeAndPass(userCode, userPass);
		// System.out.println(user);
		if (user != null) {// 判断有没有用户帐号
			session.setAttribute("login_user", user);
			result = 1;
			user.setLoginCount(user.getLoginCount() + 1);
			// user.setLoginIp(request.getRemoteAddr());
			user.setLoginDate(new Date());
		} else {
			result = 0;
		}

		return result;
	}


	@Override
	public int doBuyerLogin(String userCode, String userPass, Integer remember, HttpServletRequest request,
			HttpServletResponse response) {
		int result = 0;
		//查询买家的用户实例
		////需要对页面上提交的用户密码进行MD5加密，加完密后，用加密的字符串去数据库查询。
		String md5Pass = MD5Util.encode(userPass);
		User buyer = userDao.selectUserByCodeAndPassAndKind(userCode,md5Pass,User.USER_KIND_BUYER);
		if(buyer!=null) {
			LOG.debug(buyer.toString());
			if(buyer.getIsLock()==1) {
				HttpSession session = request.getSession();
				buyer.setLoginCount(buyer.getLoginCount()+1);
				buyer.setLoginDate(new Date());
				buyer.setLoginIp(request.getLocalAddr());
				userDao.updateById(buyer);
				session.setAttribute(ContextUtil.SESSION_LOGIN_BUYER, buyer);
				
				//此处开始处理购物车的相关数据
				Long userId=buyer.getRowId();
				
				List<Cart> cartList = cartDao.selectAllByUserId(userId);
				//Map<productId,Cart>
				/*
				 * Map<Long,Cart> cartMap = new HashMap<Long,Cart>(); if(cartList !=null &&
				 * cartList.size() >0) { for(Cart cart:cartList) { Long productId
				 * =cart.getProductId(); cartMap.put(productId, cart); } }
				 */
				//将购物车的Map数据放置到session中
				session.setAttribute(ContextUtil.SESSION_CART_NAME, cartList);
				
				
				//记住我
				if(remember!=null && remember==1) {
					StringBuilder cookieValue = new StringBuilder();
					cookieValue.append(buyer.getRowId()).append(ContextUtil.SEPERTOR).append(buyer.getUserPass());
					Cookie cookie = new Cookie(ContextUtil.COOKIE_BUYER,cookieValue.toString());
					cookie.setMaxAge(60*60*24*7);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
				result = 3;//查出并登录
			}else {
				result = 2;//被锁
			}
		}else {
			result=1;//查不出
		}
		return result;
		
	}

	@Override
	public int doAdminLogin(String userCode, String userPass, HttpServletRequest request) {
		String MD5Pass = MD5Util.encode(userPass);
		User admin = userDao.selectUserByCodeAndPassAndKind(userCode, MD5Pass, User.USER_KIND_ADMIN);
		if(admin!=null) {
			admin.setLoginCount(admin.getLoginCount()+1);
			admin.setLoginIp(request.getLocalAddr());
			admin.setLoginDate(new Date());
			System.out.println("查询到的登录用户信息++++"+admin);
			HttpSession session = request.getSession();
			session.setAttribute(ContextUtil.SESSION_LOGIN_ADMIN,admin);
			return 1;
		}else {
			return 0;
		}
	}
	//selectUserByIdAndPassAndKind
	@Override
	public void autoBuyerLogin(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if(session.getAttribute(ContextUtil.SESSION_LOGIN_BUYER)==null) {
			Cookie[] cookies = request.getCookies();
			for(Cookie cookie:cookies) {
				if(ContextUtil.COOKIE_BUYER.equals(cookie.getName())) {
					String cookieVal = cookie.getValue();
					if(cookieVal!=null) {
						String value = DESUtil.decrypt(cookieVal);
						if(value!=null) {
							System.out.println("解密后cookieVal=="+value);
							String[] array = value.split(ContextUtil.SEPERTOR);
							Long rowId = Long.parseLong(array[0]);
							String md5Pass = array[1];
							User buyer = userDao.selectUserByIdAndPassAndKind(rowId, md5Pass, User.USER_KIND_BUYER);
							if(buyer!=null && buyer.getIsLock()==0) {
								
								session.setAttribute(ContextUtil.SESSION_LOGIN_BUYER, buyer);
							}
						}
					}
				}
			}
		}
	}

	@Override
	public void initUserData() {
		User admin = userDao.selectOneByCode(ContextUtil.DEFAULT_ADMIN_CODE);
		if(admin==null) {
			admin=new User();
			admin.setUserName("管理员");
			admin.setUserCode(ContextUtil.DEFAULT_ADMIN_CODE);
			admin.setUserPass(MD5Util.encode(ContextUtil.DEFAULT_ADMIN_PASS));
			admin.setUserKind(User.USER_KIND_ADMIN);
			admin.setIsLock(0);
			admin.setLoginCount(0);
			admin.setActiveFlag(1);
			admin.setCreateBy("SYS");
			admin.setCreateDate(new Date());
			userDao.insert(admin);
		}
	}

	@Override
	public int checkUserCode(String userCode) {
		User user = userDao.selectOneByCode(userCode);
		System.out.println(user);
		if(user==null) {
			return 0;
		}else {
			return 1;
		}
	}
	

}
